from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from loguru import logger
from app.models.user import fastapi_users
from app.models.db import get_async_session, User
from app.services.task_service import TaskService


router = APIRouter(prefix="/tasks", tags=["任务管理"])


@router.get("/", summary="获取任务列表")
async def get_tasks(
    session_id: Optional[str] = Query(None, description="会话ID"),
    status: Optional[str] = Query(None, description="任务状态过滤"),
    limit: int = Query(50, ge=1, le=100, description="返回条数限制"),
    offset: int = Query(0, ge=0, description="偏移量"),
    current_user: User =  Depends(fastapi_users.current_user(active=True)),
    db: AsyncSession = Depends(get_async_session)
):
    """
    获取当前用户的任务列表
    
    支持按会话ID和状态过滤
    """
    try:
        status_filter = [status] if status else None
        
        if session_id:
            tasks = await TaskService.get_tasks_by_session(
                session_id, db, status_filter, include_results=False
            )
        else:
            tasks = await TaskService.get_tasks_by_user(
                str(current_user.id), db, status_filter, limit, offset
            )
        
        return {
            "status": "success",
            "data": [task.dict() for task in tasks],
            "total": len(tasks)
        }
        
    except Exception as e:
        logger.error(f"获取任务列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取任务列表失败")


@router.get("/{task_id}", summary="获取任务详情")
async def get_task(
    task_id: str,
    current_user: User = Depends(fastapi_users.current_user(active=True)),
    db: AsyncSession = Depends(get_async_session)
):
    """
    获取指定任务的详细信息
    """
    try:
        # 获取任务信息
        task = await TaskService.get_task_by_id(task_id, db)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")
        
        # 检查权限
        if str(task.user_id) != str(current_user.id):
            raise HTTPException(status_code=403, detail="无权限访问此任务")
        
        # 构建返回数据（包含执行结果）
        task_data = task.dict()
        
        return {
            "status": "success",
            "data": task_data
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取任务详情失败: {task_id} - {str(e)}")
        raise HTTPException(status_code=500, detail="获取任务详情失败")


@router.get("/{task_id}/results", summary="获取任务执行结果")
async def get_task_results(
    task_id: str,
    current_user: User = Depends(fastapi_users.current_user(active=True)),
    db: AsyncSession = Depends(get_async_session)
):
    """
    获取指定任务的执行结果
    """
    try:
        # 获取任务信息
        task = await TaskService.get_task_by_id(task_id, db)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")
        
        # 检查权限
        if str(task.user_id) != str(current_user.id):
            raise HTTPException(status_code=403, detail="无权限访问此任务")
        
        # 返回执行结果（从Task对象中获取）
        return {
            "status": "success",
            "data": {
                "task_id": task_id,
                "task_name": task.task_name,
                "task_type": task.task_type,
                "execution_status": task.execution_status,
                "result_data": task.get_result_data(),
                "result_summary": task.result_summary,
                "error_message": task.error_message,
                "error_details": task.get_error_details(),
                "duration_ms": task.duration_ms,
                "duration_seconds": task.get_duration_seconds(),
                "sql_query": task.sql_query,
                "rows_affected": task.rows_affected,
                "columns_info": task.get_columns_info(),
                "api_endpoint": task.api_endpoint,
                "http_status_code": task.http_status_code,
                "started_at": task.started_at.isoformat() if task.started_at else None,
                "completed_at": task.completed_at.isoformat() if task.completed_at else None,
                "created_at": task.created_at.isoformat() if task.created_at else None
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取任务执行结果失败: {task_id} - {str(e)}")
        raise HTTPException(status_code=500, detail="获取任务执行结果失败")


@router.post("/{task_id}/retry", summary="重试失败的任务（已废弃）")
async def retry_task(
    task_id: str,
    current_user: User =  Depends(fastapi_users.current_user(active=True)),
    db: AsyncSession = Depends(get_async_session)
):
    """
    重试失败的任务（已废弃功能）
    """
    raise HTTPException(
        status_code=501, 
        detail="重试功能已废弃，当前系统不支持任务重试机制"
    )


@router.post("/{task_id}/cancel", summary="取消任务")
async def cancel_task(
    task_id: str,
    current_user: User =  Depends(fastapi_users.current_user(active=True)),
    db: AsyncSession = Depends(get_async_session)
):
    """
    取消正在执行或待执行的任务
    """
    try:
        # 检查任务是否存在且属于当前用户
        task = await TaskService.get_task_by_id(task_id, db)
        if not task:
            raise HTTPException(status_code=404, detail="任务不存在")
        
        if str(task.user_id) != str(current_user.id):
            raise HTTPException(status_code=403, detail="无权限操作此任务")
        
        # 检查任务是否可以取消
        if task.is_completed():
            raise HTTPException(status_code=400, detail="已完成的任务无法取消")
        
        # 执行取消
        success = await TaskService.cancel_task(task_id, db)
        
        if success:
            return {
                "status": "success",
                "message": "任务已取消",
                "task_id": task_id
            }
        else:
            raise HTTPException(status_code=500, detail="取消任务失败")
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"取消任务失败: {task_id} - {str(e)}")
        raise HTTPException(status_code=500, detail="取消任务失败")


@router.get("/sessions/{session_id}/statistics", summary="获取会话任务统计")
async def get_session_task_statistics(
    session_id: str,
    current_user: User =  Depends(fastapi_users.current_user(active=True)),
    db: AsyncSession = Depends(get_async_session)
):
    """
    获取指定会话的任务统计信息
    """
    try:
        statistics = await TaskService.get_task_statistics(
            user_id=str(current_user.id),
            session_id=session_id,
            db=db
        )
        
        return {
            "status": "success",
            "session_id": session_id,
            "statistics": statistics
        }
        
    except Exception as e:
        logger.error(f"获取会话任务统计失败: {session_id} - {str(e)}")
        raise HTTPException(status_code=500, detail="获取任务统计失败")


@router.get("/users/{user_id}/statistics", summary="获取用户任务统计")
async def get_user_task_statistics(
    user_id: str,
    current_user: User =  Depends(fastapi_users.current_user(active=True)),
    db: AsyncSession = Depends(get_async_session)
):
    """
    获取指定用户的任务统计信息（只能查看自己的）
    """
    try:
        # 只能查看自己的统计信息
        if str(user_id) != str(current_user.id):
            raise HTTPException(status_code=403, detail="只能查看自己的任务统计")
        
        statistics = await TaskService.get_task_statistics(
            user_id=str(current_user.id),
            db=db
        )
        
        return {
            "status": "success",
            "user_id": user_id,
            "statistics": statistics
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取用户任务统计失败: {user_id} - {str(e)}")
        raise HTTPException(status_code=500, detail="获取任务统计失败")


@router.get("/pending", summary="获取待执行任务（管理员）")
async def get_pending_tasks(
    limit: int = Query(10, ge=1, le=50, description="返回条数限制"),
    current_user: User =  Depends(fastapi_users.current_user(active=True)),
    db: AsyncSession = Depends(get_async_session)
):
    """
    获取系统中待执行的任务（管理功能，暂时只返回当前用户的）
    """
    try:
        # 暂时只返回当前用户的待执行任务
        tasks = await TaskService.get_tasks_by_user(
            str(current_user.id), 
            db, 
            status_filter=["pending"], 
            limit=limit, 
            offset=0
        )
        
        return {
            "status": "success",
            "data": [task.dict() for task in tasks],
            "total": len(tasks)
        }
        
    except Exception as e:
        logger.error(f"获取待执行任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取待执行任务失败") 